const Router = require('koa-router');
const fs=require('await-fs');
const path=require('path');
const common=require('../../libs/common');

let router=new Router();

router.get('/login',async ctx=> {
    await ctx.render('admin/login',{
        HTTP_ROOT:ctx.config.HTTP_ROOT,
        errmsg: ctx.query.errmsg
    });
});

router.post('/login',async ctx=> {
    const {HTTP_ROOT}=ctx.config;
    let {username,password}=ctx.request.fields;
    let admin = JSON.parse(
        (await fs.readFile(
            path.resolve(__dirname,'../../admin.json')
        )).toString());

    function findAdmin(username){
            let a=null;
            admin.forEach(admin => {
                if(admin.username==username){
                    a=admin;
                }
            });
            return a;
        }
    let admins = findAdmin(username);
    if(!admins){
        // ctx.body='no this user';
        ctx.redirect(`${HTTP_ROOT}/admin/login?errmsg=${encodeURIComponent('用户不存在')}`)
    }else if(admins.password != common.md5(password)){
        // ctx.body='password incorrect'
        ctx.redirect(`${HTTP_ROOT}/admin/login?errmsg=${encodeURIComponent('密码错误')}`)
    }else{
        ctx.session['admin'] = username;
        ctx.redirect(`${HTTP_ROOT}/admin/`);
    }
});

// 验证是否为管理员
router.all('*',async(ctx,next)=>{
    let {HTTP_ROOT} = ctx.config;
    if(ctx.session['admin']){
        await next();
    }else{
        ctx.redirect(`${HTTP_ROOT}/admin/login`)
    }
})

router.get('/',async ctx=>{
    const {HTTP_ROOT} = ctx.config
    ctx.redirect(`${HTTP_ROOT}/admin/banner`)
})

router.use('/banner',require('./banner'));

router.use('/catalog',require('./catalog'));

router.use('/article',require('./article'));





module.exports=router.routes();